<template>
	<view>
		<view class="box">
			<view class="list">
				<text class="list-left">头像:</text>
				<view class="avatar-wrapper">
					<image class="avatar" :src="avatar" v-if="avatar" mode="aspectFill">
					</image>

					<view v-else style="
						font-size: 80rpx;    
							color: gray;
							display: flex;
							justify-content: center;
							align-items: center;
					" class="avatar qh-rt-single qh-rt-yuangong qh-user-head-img__empty-icon"></view>

					<button v-if="canIUse" class="formData-list-button" open-type="chooseAvatar"
						@chooseavatar="chooseAvatar"></button>
				</view>
			</view>

			<view class="list">
				<text class="list-left">昵称:</text>
				<view class="list-input-box">
					<input class="list-input" type="text" placeholder="请输入姓名" v-model="nickname" placeholder-class="pl"></input>
				</view>
			</view>


			<view class="list">
				<text class="list-left">姓名:</text>
				<view class="list-input-box">
					<input class="list-input" type="text" placeholder="请输入姓名" v-model="name" placeholder-class="pl"></input>
				</view>
			</view>
			<view class="list">
				<text class="list-left">性别:</text>
				<view class="list-input-box">
					<picker :value="sexIndex" class="picker" :range="sex" @change="changeSex">
						<view class="picker">{{sex[sexIndex]}}</view>
					</picker>
					<image class="right-img" src="/static/images/right.png"></image>
				</view>
			</view>
			<view class="list">
				<text class="list-left">手机:</text>
				<view class="list-input-box">
					<input class="list-input" type="tel" placeholder="请输入手机号" maxlength="11" v-model="mobile" placeholder-class="pl"></input>
					<button class="auth-button" open-type="getPhoneNumber"
					@getphonenumber="getWxPhoneNumber">点击授权</button>
				</view>
			</view>
			<!-- <view class="list" v-if="mobile.length==11&&oldMobile!=mobile">
				<text class="list-left">验证码:</text>
				<view class="list-input-box input-box-height">
					<input class="list-input" v-model="code" type="number" placeholder="请输入验证码" maxlength="6" placeholder-class="pl"></input>
				</view>
				<view v-if="count_down == 0" class="input-btn input-btn-bg flex-cn-cn" @tap="getCode">获取验证码</view>
				<view v-else class="input-btn flex-cn-cn">{{count_down}}s后重试</view>
			</view> -->
			<view class="list">
				<text class="list-left">生日:</text>
				<view class="list-input-box">
					<picker mode="date" class="picker" :value="birthday" :end="endTime" @change="changeDate">
						<view class="picker">{{birthday}}</view>
					</picker>
					<image class="right-img" src="/static/images/right.png"></image>
				</view>
			</view>

			<!-- <view v-if="set_password==0">
				<view class="list">
					<text class="list-left">新密码:</text>
					<view class="list-input-box">
						<input class="list-input" type="password"  v-model="password" maxlength="6" placeholder="请输入密码"  ></input>
					</view>
				</view>

				<view class="list">
					<text class="list-left">新密码:</text>
					<view class="list-input-box">
						<input class="list-input" type="password"  v-model="confirmationCode" maxlength="6" placeholder="请再次输入密码"  ></input>
					</view>
				</view>
			</view> -->


		</view>
		<view class="btn" @tap="save">保存</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				set_password: 0,
				pawsword: '',
				confirmationCode: '',
				endTime: '',
				sex: ['男', '女'],
				sexIndex: null,
				birthday: '',
				name: '',
				mobile: '',
				oldMobile: '',
				count_down: 0,
				code: '',
				changeAvatar: false,
				avatar:null,  //头像
				nickname: '',	//昵称
				 // #ifdef MP-WEIXIN
				 canIUse: wx.canIUse('button.open-type.chooseAvatar'), //选择头像是否可用
            	// #endif
			};
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			var y = new Date().getFullYear();
			var m = new Date().getMonth() + 1;
			var d = new Date().getDate();
			this.setData({
				endTime: y + '-' + m + '-' + d
			});
			var that = this;
			getApp().globalData.sendRequest({
				url: '/Vip/getVipData',
				loadTitle: '数据获取中...',
				success: function(res) {
					if (res.status == 1) {
						that.setData({
							birthday: res.data.birthday ? res.data.birthday : '',
							name: res.data.name ? res.data.name : '',
							mobile: res.data.mobile_phone ? res.data.mobile_phone : '',
							oldMobile: res.data.mobile_phone ? res.data.mobile_phone : '',
							sexIndex: res.data.sex == 2 ? 1 : 0,
							avatar: res.data.avatar ? res.data.avatar : '',
							nickname: res.data.nickname ? res.data.nickname : '',
							// set_password: res.data.set_password 
						});

					} else {
						getApp().globalData.showToast({
							title: res.msg,
							icon: 'none'
						});
					}	
				}
			});
		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			clearInterval(this.timer)
		},
		methods: {
			chooseAvatar(e) {
				console.log('chooseAvatar', e)
				this.changeAvatar = true;
				this.avatar = e.detail.avatarUrl;
			},
			async getWxPhoneNumber(e) {
				console.log('getWxPhoneNumber', e)
				// this.showBindPopup = false;
				// this.isBind = false;
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					this.getUserPhone({
						new_phone: 1,
						iv: e.detail.iv,
						code: e.detail.code,
						appId: getApp().globalData.XcxData.appid,
						verify_vip: this.$store.userInfo.type == 1 ? 0 : 1,
					}, e);
				} else {
					// if (e.currentTarget.dataset.type == 2) {
					// 	this.isBind = true;
					// }
					// this.showInputPhone = true;
					uni.showToast({
						title: '您已拒绝授权手机号',
						icon: 'none',
						duration: 1000,
						mask: false
					});
				}
			},

			async  uploadAvatar(avatar, changeAvatar) {
				if (!changeAvatar) return; // 如果没有更改头像，直接返回

				try {
					const res = await upload({
					url: '/SmallProgramApi/Image/uploadAvatar',
					path: avatar,
					name: 'avatar',
					}, true);

					// 上传成功后更新头像路径并重置 changeAvatar 标志
					avatar = res.data.path;
					changeAvatar = false;
				} catch (error) {
					uni.showToast({
					title: '头像上传失败',
					icon: 'none',
					});
				}

				return { avatar, changeAvatar }; // 返回更新后的 avatar 和 changeAvatar 状态
				},


			// 获取用户手机号
			async getUserPhone(data, e) {

			const res = await this.$request('SmallProgramApi/Vip/getPhone', data);
				if (res.status == 1) {
					console.log(res, 'res')
					this.mobile = res.data.phoneNumber
					uni.showToast({
						title: '手机号获取成功',
						icon: 'success',
						duration: 1000
					})
				} else {
					uni.showToast({
						title: '获取手机号失败',
						icon: 'none',
						duration: 1000
					})
				}
			},
			/**
			 * 获取验证码
			 */
			getCode() {
				if (!/1[356789]\d{9}/.test(this.mobile)) return uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				getApp().globalData.sendRequest({
					url: '/Vip/getCode',
					loadTitle: '发送中...',
					data: {
						phone: this.mobile
					},
					success: (res) => {
						if (res.status == 1) {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								duration: 1000
							});
							this.count_down = 60;
							this.timer = setInterval(() => {
								this.count_down--;
								if (this.count_down == 0) {
									clearInterval(this.timer);
								}
							}, 1000);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 1500
							});
						}
					}
				});
			},

			/**
			 * 选择性别
			 */
			changeSex: function(e) {
				this.setData({
					sexIndex: e.detail.value
				});
			},

			/**
			 * 选择生日
			 */
			changeDate: function(e) {
				this.setData({
					birthday: e.detail.value
				});
			},

			/**
			 * 保存
			 */
			save: function() {
				var that = this;
				var name = this.name;
				var mobile = this.mobile;
				var birthday = this.birthday;
				var sexIndex = this.sexIndex;
				var avatar = '';
				var nickname = '';	
				var code = '';
				if (name == '' || name.trim() == '') {
					getApp().globalData.showToast({
						title: '请输入姓名',
						icon: 'none'
					});
					return;
				}

				this.uploadAvatar(this.avatar, this.changeAvatar).then(({ avatar, changeAvatar }) => {
					this.avatar = avatar;
					this.changeAvatar = changeAvatar;
				});

				if (!/1[356789]\d{9}/.test(mobile)) {
					getApp().globalData.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

			
				

				// if (mobile != that.oldMobile && (that.code == '' || that.code.length < 6)) {
				// 	getApp().globalData.showToast({
				// 		title: '请输入验证码',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }

				code = that.code;

				if (birthday == '' || birthday.trim() == '') {
					getApp().globalData.showToast({
						title: '请选择生日',
						icon: 'none'
					});
					return;
				}

				if (sexIndex === '') {
					getApp().globalData.showToast({
						title: '请输入性别',
						icon: 'none'
					});
					return;
				}

				if(that.avatar == '' || that.avatar == null){
					getApp().globalData.showToast({
						title: '请上传头像',
						icon: 'none'
					});
					return;
				}

				
				// if (!that.confirmationCode) {
				// 	getApp().globalData.showToast({
				// 		title: '请确认密码',
				// 		icon: 'none'
				// 	})
				// 	return
				// }

				// if (that.password !== that.confirmationCode) {
				// 	getApp().globalData.showToast({
				// 		title: '两次密码输入不一致',
				// 		icon: 'none'
				// 	})
				// 	return
				// }

				avatar =  that.avatar
				nickname =  that.nickname
				getApp().globalData.sendRequest({
					url: '/Vip/editVipData',
					loadTitle: '提交中...',
					data: {
						name: name,
						mobile: mobile,
						birthday: birthday,
						sex: sexIndex == 1 ? 2 : 1,
						avatar: this.avatar,
                		nickname: this.nickname,
						// code: code
					},
					success: function(res) {
						if (res.status == 1) {
							getApp().globalData.showToast({
								title: res.msg
							});
							setTimeout(function() {
								uni.navigateBack({
									delta: 1
								});
							}, 1000);
							getApp().globalData.userLogin(async () => {
								uni.navigateBack();
							});
						} else {
							getApp().globalData.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					}
				});
			}
		}
	};
</script>
<style>
	@import "./vipInfo.css";


</style>

<style lang="scss" scoped>

.auth-button {
        color: gray;
        font-size: 24rpx;
        padding: 10rpx 30rpx;
        border-radius: 30rpx;
        margin-left: 20rpx;
        border: none;
        line-height: 1.5;
        height: auto;
        flex-shrink: 0;

        &::after {
            border: none;
        }

        &:active {
            opacity: 0.8;
        }
    }
	.avatar-wrapper {
                    position: relative;
                    width: 120rpx;
                    height: 120rpx;

                    .avatar {
                        width: 100%;
                        height: 100%;
                        border-radius: 50%;
                    }

                    .formData-list-button {
                        position: absolute;
                        left: 0;
                        top: 0;
                        width: 100%;
                        height: 100%;
                        opacity: 0;
                        z-index: 1;
                        padding: 0;
                        margin: 0;

                        &::after {
                            border: none;
                        }
                    }
                }
	</style>
